package com.sweet.spheredemo.dao;

import com.sweet.spheredemo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.List;
import java.util.Objects;

@Repository
public class UserDao implements RowMapper<User> {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  public List<User> findAll() {
    return jdbcTemplate.query("select id, name, age from user", this);
  }

  public List<User> findAll(long start, int size) {
    System.out.println("start: " + start + ", size: " + size);

    return jdbcTemplate.query("select id, name, age from user limit ?,?", this, start, size);
  }

  public User findOne(long id) {
    return jdbcTemplate.queryForObject("select id, name, age from user where id = ?",
        this,  id);
  }

  public Long insert(User user) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(connection -> {
      PreparedStatement preparedStatement = connection.prepareStatement("insert into user (name, age) VALUES (?,?)",
          Statement.RETURN_GENERATED_KEYS);
      preparedStatement.setString(1, user.getName());
      preparedStatement.setInt(2, user.getAge());
      return preparedStatement;
    }, keyHolder);
    long id = Objects.requireNonNull(keyHolder.getKey()).longValue();
    user.setId(id);
    return id;
  }

  public void update(User user) {
    jdbcTemplate.update("update user set name = ?, age = ? where id = ?", user.getName(), user.getAge(), user.getId());
  }

  public void delete(long id) {
    jdbcTemplate.update("delete from user where id = ?", id);
  }

  @Override
  public User mapRow(ResultSet resultSet, int i) throws SQLException {
    long id = resultSet.getLong("id");
    String name = resultSet.getString("name");
    int age = resultSet.getInt("age");
    return new User(id, name, age);
  }
}
